package icasue.reflect.handles.util;

import icasue.reflect.annotations.NotNull;
import icasue.reflect.handles.classes.ClassOF;
import icasue.reflect.handles.object.ObjectOF;
import icasue.reflect.handles.predicate.SureOF;

import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * @Author: Qiao Hang
 * @CreateDate: 2020/12/25 上午10:43
 * @UpdateDate:
 * @Description:
 */
public class OFUtil {

    public static <T> T cast(Object inst, @NotNull Class<T> type){
        return ObjectOF.isNull_.test(inst) || ObjectOF.isNull_.test(type)
                ? null : (T)ClassOF.cast_.apply(type,inst);
    }

    public static <T> List<T> castMulti(Object list, @NotNull Class<T> type){
        return ObjectOF.isNull_.test(list) || ObjectOF.isNull_.test(type)
                ? null : (List<T>)ClassOF.cast_.apply(List.class,list);
    }

    public static <T> List<T> aryToList(Object ary, @NotNull Class<T> type){
        SureOF.notNull(ary,"OFUtil :: aryToList require not null ary.");
        SureOF.notNull(type,"OFUtil :: aryToList require not null unit Type.");
        int length = Array.getLength(ary);
        List<T> targets = length <= 0 ? Collections.EMPTY_LIST : new ArrayList<T>(length);
        for (int i = 0; i < length; i++)
            targets.add(cast(Array.get(ary,i),type));
        return targets;
    }

    public static <T> T[] listToAry(Object list, @NotNull Class<T> type){
        SureOF.notNull(list,"OFUtil :: listToAry require not null List.");
        SureOF.notNull(type,"OFUtil :: listToAry require not null unit Type.");
        List<T> cast = (List<T>) list;
        T[] targets = (T[])Array.newInstance(type,cast.size());
        targets = cast.toArray(targets);
        return targets;
    }

}
